import { userInfo, logout } from '@/api/login'
import { defineStore } from 'pinia'
import { message } from 'ant-design-vue';
export const useUserStore = defineStore(
  // 唯一ID
  'user',
  {
    state: () => ({
      userInfo: JSON.parse(window.localStorage.getItem('user-info')) || {}
    }),
    getters: {
      // 通过 this 获取状态（注意this指向）
      nickname: () => this.userInfo.nickname,
      avatar: () => this.userInfo.avatar
    },
    actions: {
      // 获取用户信息
      GetUserInfo () {
        return new Promise((resolve, reject) => {
          userInfo().then(res => {
            this.userInfo = {...res}
            window.localStorage.setItem('user-info', JSON.stringify(res))
            resolve(res)
          }).catch(error => {
            message.error(error.message || '获取用户信息失败')
            reject(error)
          })
        })
      },
      // 登出
      Logout () {
        window.localStorage.removeItem('access-token')
        window.localStorage.removeItem('user-info')
        this.userInfo = {}
        message.info('登出成功')
      }
    }
  }
)